import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import {
  getArticlesByIdAction,
  updateArticlesByIdAction,
} from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useDispatch } from 'react-redux';

export default function ArticleList() {
  const dispatch = useDispatch();
  const { currentId } = useAppSelector((state) => state.channel);
  const { articleList } = useAppSelector((state) => state.article);
  const pre_timestamp = articleList[currentId]?.pre_timestamp;

  const list = articleList[currentId]?.results || [];
  const loadMore = async () => {
    await dispatch(
      updateArticlesByIdAction({
        channel_id: currentId,
        timestamp: pre_timestamp,
      })
    );
  };

  // 2.onRefresh触发下拉
  const handleRefresh = async () => {
    // 3. 使用getArtilesByIdAction请求数据
    await dispatch(getArticlesByIdAction({ channel_id: currentId }));
  };
  return (
    // 1. PullToRefres包住所有的代码
    <PullToRefresh onRefresh={handleRefresh}>
      <div>
        {list.map((item) => {
          return <ArticleItem itemData={item as any} key={item.art_id} />;
        })}

        {!!list.length && (
          <InfiniteScroll loadMore={loadMore} hasMore={!!pre_timestamp} />
        )}
      </div>
    </PullToRefresh>
  );
}
